﻿using Common.Dtos;
using Common.Helper;
using MaterialDesignThemes.Wpf;
using Newtonsoft.Json;
using Prism.Commands;
using Prism.Events;
using Prism.Ioc;
using Prism.Regions;
using Sigma.Admin.Client.DialogAware;
using Sigma.Admin.Client.Extensions;
using Sigma.Admin.Client.Services;
using Sigma.Admin.Client.Views;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;

namespace Sigma.Admin.Client.ViewModels
{
    [RegionMemberLifetime(KeepAlive = false)]
    public class PermissionViewModel : NavigationViewModel
    {
        private readonly IPermissionService _permissionService;
        private readonly IUserService _userService;
        private readonly IRegionManager _regionManager;
        private  DrawerHost _drawerHost;
        
        public PermissionViewModel(IRegionManager regionManager, IEventAggregator ea, IUserService userService, IPermissionService permissionService,IContainerProvider containerProvider, IDialogHostService dialog) : base(ea, containerProvider)
        {
            _permissionService = permissionService;
            _userService = userService;
           
            _regionManager = regionManager;
            OpenDrawerCommand = new DelegateCommand<int?>(OpenBottomDrawer);
            SaveEditCommand = new DelegateCommand(SaveEditAsync);
        }
        #region 数据集合
        private ObservableCollection<PermissionDto> pers;

        public ObservableCollection<PermissionDto> Pers
        {
            get { return pers; }
            set { pers = value; RaisePropertyChanged(); }
        }
        private ObservableCollection<UsersDto> users;

        public ObservableCollection<UsersDto> Users
        {
            get { return users; }
            set { users = value; RaisePropertyChanged(); }
        }
        #endregion

        private ObservableCollection<PermissionDto> _userPers;

        public ObservableCollection<PermissionDto> UserPers
        {
            get { return _userPers; }
            set { _userPers = value; RaisePropertyChanged(); }
        }

        private UsersDto SelectedUser { get; set; } 

        public DelegateCommand<int?> OpenDrawerCommand { get; private set; }
        public void OpenBottomDrawer(int? id)
        {
            var user = BackUpHelper<UsersDto>.DeepCopy(users.Where(x => x.Id.Equals(id)).FirstOrDefault());//拿到btn所在行的user
            SelectedUser = user;
            var permissions = BackUpHelper<ObservableCollection<PermissionDto>>.DeepCopy(pers);
            user.PermissionKey.ForEach(x =>
            {
                var key = permissions.Where(p => p.Id == x).FirstOrDefault();
                key.IsCheck = true;
            });
            UserPers = permissions;//选中的key
            var view =_regionManager.Regions["ContentRegion"].ActiveViews.FirstOrDefault() as PermissionView;
            var drawer = (DrawerHost)view.FindName("DrawerHost");
            _drawerHost = drawer;
            drawer.IsBottomDrawerOpen = true;
        }
        public DelegateCommand SaveEditCommand { get; private set; }
        async void SaveEditAsync()
        {
            var list = new List<int>();
            UserPers.ToList().ForEach(x =>
            {
                if (x.IsCheck)
                    list.Add(x.Id);
            });
            SelectedUser.PermissionKey = list;
            var res = await _userService.EditPKey(SelectedUser);
            if (res.Status)
            {

                _drawerHost.IsBottomDrawerOpen = false;
                await GetDataAsync();
                _ea.SendMessage(res.Message);
            }
            else
                _ea.SendMessage(res.Message);
        }

        async Task GetDataAsync()
        {
            UpdateLoading(true);

            var res = await _permissionService.GetAllPermission();
            var resU = await _userService.GetAllUser();
            if (res.Status&& resU.Status)
            {
                Pers = new ObservableCollection<PermissionDto>(res.Result);
                Users = new ObservableCollection<UsersDto>(resU.Result);
            }
            else
            {
                _ea.SendMessage(res.Message);
            }
            UpdateLoading(false);
        }
        public override async void OnNavigatedTo(NavigationContext navigationContext)
        {
            base.OnNavigatedTo(navigationContext);
            if(navigationContext.Parameters.GetValue<bool>("IsNewInstance"))//创建新实例才刷新
                await GetDataAsync();
        }
    }
}
